﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using Aandelendelen.Obs;

namespace Aandelendelen.Stocks
{
	public class StockMatchHelper : Dictionary<string, NameValueCollection>
	{
		StockIDCollection stockIDs = StockIDCollection.GetInstance();

		public void Add(string item, string name, string value)
		{
			NameValueCollection nv = null;
			if (this.TryGetValue(item, out nv) == false)
			{
				nv = new NameValueCollection(8);
				this[item] = nv;
			}

			nv[name] = value;
		}

		public void PopulateStocks(StockCollection stocks, string market)
		{
			foreach (NameValueCollection nv in this.Values)
			{
				string name = nv["name"];

				// If not in StockID.xml, discard
				int id;
				if (this.stockIDs.TryGetValue(name, out id) == false)
					continue;

				decimal curPrice = decimal.Parse(nv["trade"]);
				decimal diffPrice = decimal.Parse(nv["change"]);
				decimal prevPrice = curPrice - diffPrice;
				string increase = nv["pctchange"];
				Rate curRate = new Rate(curPrice, DateTime.Parse(nv["tradetime"]));
				Rate prevRate = new Rate(prevPrice, DateTime.MinValue);

				stocks[id] = new Stock(name) { Market = market, Increase = increase, CurrentRate = curRate, ClosingRate = prevRate, ID = id }; 				
			}
		}
	}
}